
class TangrenjieInfo extends AbstractPlugin {

  static BASE_URL = 'https://www.trjvod.com';

  async fetchWebsiteInfo() {
    const url = window.location.href;
    const checkRegex = new RegExp(`^${TangrenjieInfo.BASE_URL}/index\.php/vod/(detail|play)/id/`);
    if(!checkRegex.test(url)) {
      return null;
    }

    const parser = new DOMParser();
    const doc = parser.parseFromString(document.body.outerHTML, 'text/html');

    const playSources = [];

    const playSource = doc.querySelector('.play_source, .playlist');
    if(!playSource) {
      return null;
    }
    const sources = Array.from(playSource.querySelectorAll('.play_source_tab .wo, .play_source_tab a'));
    const titles = sources.map(source => {
      if (source.classList.contains('wo')) {
        return source.getAttribute('alt');
      }
      return source.textContent.trim();
    });
    const playLists = playSource.querySelectorAll('.playlist_full');
    playLists.forEach((playlist, index) => {
      const title = titles[index];
      const totalEpisodes = playlist.querySelectorAll('.content_playlist a');

      const episodes = [];
      totalEpisodes.forEach((item) => {
        const episodeItem = new Episode();
        episodeItem.title = item.textContent.trim();
        const href = item.getAttribute('href');
        episodeItem.link = href.startsWith('/') ? `${TangrenjieInfo.BASE_URL}${href}` : href;
        episodes.push(episodeItem);
      })

      playSources.push(new Source({
        title: title,
        episodes: episodes
      }));
    });

    const websiteInfo = new WebsiteInfo();
    websiteInfo.type = 'video';
    websiteInfo.title = doc.querySelector('.hd_tit').textContent.trim();
    websiteInfo.link = url;
    websiteInfo.sources = playSources;

    const playRegex = /\/vod\/play\//;
    if(playRegex.test(url)) {
      websiteInfo.playUrl = this.getPlayUrlFromBody(document.body.outerHTML);
      const curEp = playSource.querySelector('.playlist_full .active a');
      if(curEp) {
        const href = curEp.getAttribute('href');
        const curEpLink = href.startsWith('/') ? `${TangrenjieInfo.BASE_URL}${href}` : href;
        [websiteInfo.sourceIndex, websiteInfo.episodeIndex] = AbstractPlugin.findEpisode(playSources, curEpLink);
      }
    }

    return websiteInfo;
  }

  async fetchPlayUrlInfo(url) {
    const http_headers = {
      'User-Agent': TangrenjieInfo.DEFAULT_USER_AGENT,
      'Origin': TangrenjieInfo.BASE_URL,
    };
    const result = await doHttpRequestSync(url, { headers: http_headers });
    if(result.status !== 'success') {
      return null;
    }
    return this.getPlayUrlFromBody(result.body);
  }

  getPlayUrlFromBody(body) {
    const regex = /player_aaaa\s*=\s*(\{(?:[^{}]|{(?:[^{}]|{[^{}]*})*})*})/;
    const match = body.match(regex);
    if(!match) {
      return null;
    }

    try {
      const data = JSON.parse(match[1]);
      const playUrl = new PlayUrlInfo();
      playUrl.type = 'video';
      playUrl.urls = [decodeURIComponent(data['url'])];
      return playUrl;
    } catch (error) {
      return null;
    }
  }

}
Registry.registerClass("TangrenjieInfo", new TangrenjieInfo());